<!--
 * @Author: your name
 * @Date: 2020-04-26 01:16:49
 * @LastEditTime: 2020-06-14 18:59:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \museweb\src\views\musePage\point\changePoint.vue
 -->
<template>
  <d2-container>
    <el-row>
      <el-col :lg="12">
        <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="100px">
          <el-form-item label="手机号" prop="user">
            <el-input style="width: 80%" placeholder="手机号" v-model="cellPhone"></el-input>
            <el-button type="primary" style="float: right;" @click="getUserLastFour">搜索</el-button>
            <div style="margin-top:10px" v-if="choosedAryByUser.length > 0">
              <el-table :data="choosedAryByUser" width="100%" ref="ref_table">
                <el-table-column prop="nickName" label="昵称" />
                <el-table-column prop="cellphone" label="手机号" />
                <el-table-column prop="userPoint.current" label="可用积分" />
                <el-table-column prop="userPoint.pendingPoint" label="待审核积分" />
              </el-table>
            </div>
          </el-form-item>
          <el-form-item label="关联的门店" prop="store">
            <el-button type="primary" @click="fnOpenPopup">选择门店</el-button>
            <div style="margin-top:10px" v-if="choosedAryByStore.length > 0">
              <el-table :data="choosedAryByStore" width="100%" ref="ref_table">
                <el-table-column prop="name" label="名称" />
                <el-table-column prop="brief" label="简介">
                  <template slot-scope="{row: {brief}}">
                    <span>{{brief | subStr(10)}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <el-form-item label="账单号" prop="billNumber">
            <el-input placeholder="账单号" v-model="detailForm.billNumber"></el-input>
          </el-form-item>
          <el-form-item label="消费价格" prop="amount">
            <el-input placeholder="消费价格" v-model="detailForm.amount"></el-input>
          </el-form-item>
          <el-form-item label="获得积分" v-if="choosedAryByStore.length > 0 && choosedAryByUser.length > 0">
            <el-input v-if="!detailForm.notGivePoint" placeholder="获得积分" v-model="getPoint" readonly></el-input>
            <el-input v-else placeholder="获得积分" value="0" readonly></el-input>
          </el-form-item>
          <el-form-item label="使用积分" prop="usePoint">
            <el-radio v-model="detailForm.usePoint" :label="0">不使用</el-radio>
            <el-radio v-model="detailForm.usePoint" :label="1">使用</el-radio>
          </el-form-item>
          <el-form-item label="积分" prop="point" v-if="detailForm.usePoint === 1">
            <el-input placeholder="积分" v-model="detailForm.point"></el-input>
          </el-form-item>
          <el-form-item v-if="false" label="需支付价格" prop="payPrice">
            <el-input disabled placeholder="支付价格" v-model="payPrice"></el-input>
          </el-form-item>
          <el-form-item v-if="false" label="备注" prop="memo">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="备注"
              v-model="detailForm.memo"
            ></el-input>
          </el-form-item>
          <el-form-item prop="payPrice" v-if="false">
            <el-checkbox v-model="detailForm.givePoint">超出消费金额不计算积分</el-checkbox>
          </el-form-item>
          <el-form-item prop="notGivePoint">
            <el-checkbox v-model="detailForm.notGivePoint">账单不计算积分</el-checkbox>
          </el-form-item>
          <el-form-item label="账单" prop="billImage">
              <banner v-model="detailForm.billImage"></banner>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
            <el-button @click="resetForm('detailForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-dialog title="门店列表" :visible.sync="dialogDataVisible">
      <el-table
        :data="tableData"
        width="100%"
        ref="ref_table"
        highlight-current-row
        @current-change="value => handleRadioTable(value, 'store')"
      >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="brief" label="简介">
          <template slot-scope="{row: {brief}}">
            <span>{{brief | subStr(10)}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="muse_pagination"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="paging.pageSizeAry"
        :page-size="paging.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDataVisible = false; choosedDataObjByStore = {}">取 消</el-button>
        <el-button type="primary" @click="dialogDataVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="用户列表" :visible.sync="userDialogVisible">
      <el-table
        :data="userTableData"
        width="100%"
        ref="ref_table"
        highlight-current-row
        @current-change="value => handleRadioTable(value, 'user')"
      >
        <el-table-column prop="nickName" label="昵称" />
        <el-table-column prop="cellphone" label="手机号" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => {userDialogVisible = false; choosedDataObjByUser = {}}">取 消</el-button>
        <el-button type="primary" @click="userDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import tableMixin from "../mixins/tableMixin";
import banner from '@/components/muse/banner/banner'
import {
  getBanner,
  getUserLastFour,
  getStoreList,
  addUserExpenseHistory,
  recallUserExpenseHistory,
  changeUserExpenseHistory
} from "@/api/admin";
export default {
  name: "changePoint",
  mixins: [tableMixin],
  components: { banner },
  data() {
    return {
      cellPhone: "",
      detailForm: {
        user: "",
        store: "",
        amount: "",
        // payPrice: '',
        usePoint: 0,
        point: 0,
        memo: "",
        billNumber: "",
        billImage: [],
        notGivePoint: false
        // givePoint: false
      },
      rules: {
        user: [{ required: true, message: "请选择用户", trigger: "blur" }],
        store: [{ required: true, message: "请选择门店", trigger: "blur" }],
        amount: [
          { required: true, message: "请输入消费金额", trigger: "blur" }
        ],
        usePoint: [
          { required: true, message: "请选择是否使用积分", trigger: "blur" }
        ],
        point: [{ required: true, message: "请输入积分数额", trigger: "blur" }]
      },
      choosedDataObjByStore: {},
      choosedDataObjByUser: {},
      userTableData: [],
      dialogDataVisible: false,
      userDialogVisible: false,
    };
  },
  computed: {
    payPrice() {
      if (this.detailForm.usePoint === 0) {
        this.detailForm.payPrice = this.detailForm.amount;
      } else {
        this.detailForm.payPrice =
          this.detailForm.amount - this.detailForm.point;
      }
      return this.detailForm.payPrice;
    },
    choosedAryByStore() {
      return Object.keys(this.choosedDataObjByStore ? this.choosedDataObjByStore: {}).length > 0
        ? [this.choosedDataObjByStore]
        : [];
    },
    choosedAryByUser() {
      return Object.keys(this.choosedDataObjByUser ? this.choosedDataObjByUser : {}).length > 0
        ? [this.choosedDataObjByUser]
        : [];
    },
    getPoint() {
      // givePoint
      const attribute = this.choosedDataObjByUser.vip ? this.choosedDataObjByStore.attributeVIP : this.choosedDataObjByStore.attribute
      let countAmount = this.detailForm.amount
      countAmount = countAmount - (this.detailForm.usePoint ? this.detailForm.point : 0)
      // if(this.detailForm.givePoint) {
      //   countAmount = 0
      // } else {
      //   countAmount = countAmount - (this.detailForm.usePoint ? this.detailForm.point : 0)
      // }
      return Math.round(countAmount * attribute * 0.01)
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addUserExpenseHistory();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs["detailForm"].resetFields();
      this.choosedDataObjByStore = {};
      this.choosedDataObjByUser = {};
      this.cellPhone = "";
    },

    async addUserExpenseHistory() {
      // this.detailForm.givePoint = this.detailForm.givePoint ? 0 : 1
      this.detailForm.notGivePoint = this.detailForm.notGivePoint ? 1 : 0
      console.log(this.detailForm.amount < this.detailForm.point, this.detailForm.amount, this.detailForm.point)
      if(this.detailForm.usePoint === 1 && +this.detailForm.amount < +this.detailForm.point) {
        this.$alert('消费金额不能小于使用积分', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            
          }
        });
        return
      }
      const params = Object.assign({}, this.detailForm);
      const res = await addUserExpenseHistory(params);
      if (res.code === 200) {
        this.$message({
          message: "扫码消费成功",
          type: "success"
        });
        this.resetForm();
      }
    },

    // 关联门店相关------------------------------------
    // 打开门店弹框
    fnOpenPopup() {
      this.dialogDataVisible = true;
      this.getTableData();
    },
    // 获得门店列表
    async getTableData(value, type) {
      let params = {
        page:
          type === "page"
            ? value
              ? value
              : this.paging.page
            : this.paging.page,
        pageSize:
          type === "pageSize"
            ? value
              ? value
              : this.paging.pageSize
            : this.paging.pageSize
      };
      const {
        code,
        data: { total, currentPage, data, pageSize }
      } = await getStoreList(params);
      this.paging.total = total;
      this.paging.pageSize = pageSize;
      this.paging.page = currentPage;
      this.tableData = data;
    },
    handleRadioTable(value, type) {
      if (type === "store") {
        this.choosedDataObjByStore = value;
        this.detailForm.store = this.choosedDataObjByStore._id;
      } else {
        this.choosedDataObjByUser = value;
        this.detailForm.user = this.choosedDataObjByUser._id;
      }
    },

    /**
     * @description: 根据后四位手机号获取信息
     * @param {type}
     * @return:
     */

    async getUserLastFour() {
      const res = await getUserLastFour({ cellphone: this.cellPhone });
      this.userDialogVisible = true;
      this.userTableData = res.data;
    }
  }
};
</script>

<style scoped>
.from_width {
  width: 40%;
}
</style>
